package org.goldfish.library_system.service;

import org.goldfish.library_system.entity.BorrowRecord;
import org.goldfish.library_system.entity.Book;
import org.goldfish.library_system.repos.BorrowRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class BorrowRecordService {
    @Autowired
    private BorrowRecordRepository borrowRecordRepository;

    @Autowired
    private BookService bookService;

    // 获取所有借阅记录
    public List<BorrowRecord> findAllBorrowRecords() {
        return borrowRecordRepository.findAll();
    }

    // 根据读者 ID 获取借阅记录
    public List<BorrowRecord> findBorrowRecordsByReaderId(Long readerId) {
        return borrowRecordRepository.findByReaderId(readerId);
    }

    // 根据图书 ID 获取借阅记录
    public List<BorrowRecord> findBorrowRecordsByBookId(Long bookId) {
        return borrowRecordRepository.findByBookId(bookId);
    }

    // 获取所有逾期记录
    public List<BorrowRecord> findOverdueRecords() {
        return borrowRecordRepository.findByOverdue(true);
    }

    // 添加或更新借阅记录
    public BorrowRecord saveBorrowRecord(BorrowRecord borrowRecord) {
        // 更新库存
        bookService.updateStock(borrowRecord.getBook().getId(), -1);

        // 保存借阅记录
        borrowRecord.setBorrowDate(LocalDateTime.now());
        borrowRecord.setOverdue(false);
        return borrowRecordRepository.save(borrowRecord);
    }

    // 归还图书
    public BorrowRecord returnBook(Long borrowId) {
        Optional<BorrowRecord> optionalRecord = borrowRecordRepository.findById(borrowId);
        if (optionalRecord.isPresent()) {
            BorrowRecord record = optionalRecord.get();
            record.setReturnDate(LocalDateTime.now());

            // 更新库存
            bookService.updateStock(record.getBook().getId(), 1);

            // 检查是否逾期
            if (record.getBorrowDate().plusDays(14).isBefore(record.getReturnDate())) {
                record.setOverdue(true);
            }
            return borrowRecordRepository.save(record);
        }
        throw new IllegalArgumentException("Borrow record not found with ID: " + borrowId);
    }

    // 删除借阅记录
    public void deleteBorrowRecord(Long id) {
        borrowRecordRepository.deleteById(id);
    }
}